package com.lz.rocketmq.consumer.common.utils;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

public class JsonUtils {

    /**
     * 将Map转换为JSON字符串。
     * 注意：此方法简单处理了基本的Map结构，对于特殊字符如双引号和反斜杠，
     * 会进行必要的转义以保持JSON的有效性，但不使用任何外部库。
     *
     * @param map 待转换的Map对象
     * @return 转换后的JSON字符串
     */
    public static String mapToJson(Map<String, Object> map) {
        Writer writer = new StringWriter();
        try {
            writeMap(writer, map);
            return writer.toString();
        } catch (Exception e) {
            throw new RuntimeException("Error converting map to JSON", e);
        }
    }

    private static void writeMap(Writer writer, Map<String, Object> map) throws Exception {
        writer.write('{');
        boolean first = true;
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (!first) {
                writer.write(',');
            }
            writeString(writer, entry.getKey());
            writer.write(':');
            writeValue(writer, entry.getValue());
            first = false;
        }
        writer.write('}');
    }

    private static void writeString(Writer writer, String value) throws Exception {
        writer.write('"');
        for (int i = 0; i < value.length(); i++) {
            char c = value.charAt(i);
            writer.write(c);
        }
        writer.write('"');
    }

    private static void writeValue(Writer writer, Object value) throws Exception {
        if (value instanceof String) {
            writeString(writer, (String) value);
        } else if (value instanceof Number || value instanceof Boolean) {
            writer.write(value.toString());
        } else if (value instanceof Map) {
            writeMap(writer, (Map<String, Object>) value);
        } else {
            // 对于其他类型的值，这里简单地转换为字符串
            writeString(writer, value.toString());
        }
    }
}
